/**
 * 京东联盟京粉精选商品查询模块
 * @version 1.0.0
 * @author 开发者
 * @see {@link https://union.jd.com/openplatform/api/1229|京东联盟API文档}
 */

const {
  normalizePayload,
  normalizeDbConfig,
  buildSignParams,
  buildJdSign,
  parseJdQueryResult,
  persistDocs,
  JD_API_URL,
  mapRankGoodsDoc,
  buildQueryResultMeta
} = require('./@utils')

/**
 * 京粉精选优质商品查询接口
 *
 * @param {object} payload 请求参数
 * @param {object} [payload.auth] 认证信息
 * @param {object} payload.query 查询参数
 * @param {number} payload.query.eliteId 频道ID
 * @param {number} [payload.query.pageIndex=1] 页码
 * @param {number} [payload.query.pageSize=20] 每页数量（最大60）
 * @param {string} [payload.query.sortName] 排序字段
 * @param {string} [payload.query.sort] 排序方式（asc/desc）
 * @param {string} [payload.query.pid] 推广位ID
 * @param {number} [payload.query.resourceId] 资源位ID
 * @param {number} [payload.query.channelId] 渠道ID
 * @param {object} [payload.options] 可选配置
 * @param {string|object} [payload.options.db] 数据库配置
 * @returns {Promise<{requestParams: object, response: any, queryResult?: object, baseGoods?: any[], dbResult?: any}>}
 * @example
 * // 新格式
 * await queryJingfenGoods({
 *   query: { eliteId: 1, sortName: 'price', sort: 'asc' },
 *   options: { db: 'jd_jingfen_goods' }
 * })
 */
async function queryJingfenGoods(payload) {
  const { auth, query, options } = normalizePayload(payload)

  const {
    goodsReq,
    eliteId,
    pageIndex = 1,
    pageSize = 50, // 默认50，也是最大值
    sortName,
    sort,
    pid,
    resourceId,
    channelId
  } = query

  let finalGoodsReq = goodsReq
  if (!finalGoodsReq) {
    if (typeof eliteId !== 'number') {
      throw new Error('eliteId不能为空')
    }
    const safePageSize = Math.max(1, Math.min(pageSize, 50)) // 最大50
    finalGoodsReq = {
      eliteId,
      pageIndex,
      pageSize: safePageSize
    }
    if (typeof sortName === 'string' && sortName.trim()) {
      finalGoodsReq.sortName = sortName.trim()
    }
    if (typeof sort === 'string' && sort.trim()) {
      finalGoodsReq.sort = sort.trim()
    }
    if (typeof pid === 'string' && pid.trim()) {
      finalGoodsReq.pid = pid.trim()
    }
    if (typeof resourceId === 'number') {
      finalGoodsReq.resourceId = resourceId
    }
    if (typeof channelId === 'number') {
      finalGoodsReq.channelId = channelId
    }
  }

  const { params, appSecret: secret } = buildSignParams({
    appKey: auth.appKey,
    appSecret: auth.appSecret,
    method: 'jd.union.open.goods.jingfen.query',
    businessParams: {
      goodsReq: finalGoodsReq
    },
    timestamp: options.timestamp,
    version: options.version,
    format: options.format,
    signMethod: options.signMethod,
    accessToken: auth.accessToken
  })
  const { sign } = buildJdSign(secret, params)
  const requestParams = {
    ...params,
    sign
  }

  const { status, data } = await uniCloud.httpclient.request(JD_API_URL, {
    method: 'POST',
    data: requestParams,
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded',
    timeout: 10000
  })

  if (status !== 200) {
    throw new Error(`京东联盟接口请求失败，HTTP状态码：${status}`)
  }

  const queryResult = parseJdQueryResult(data, 'jd_union_open_goods_jingfen_query_responce')
  const baseGoods = Array.isArray(queryResult?.data) ? queryResult.data : []

  let dbResult
  const dbConfig = normalizeDbConfig(options.db)
  if (dbConfig) {
    dbResult = await persistDocs({
      collectionName: dbConfig.collection,
      list: baseGoods,
      transform: mapRankGoodsDoc,
      uniqueKeys: dbConfig.uniqueKeys,
      extraDocFields: {
        requestParams,
        queryResultMeta: buildQueryResultMeta(queryResult),
        ...(dbConfig.extraFields || {})
      }
    })
  }

  if (options.debug) {
    return {
      requestParams,
      response: data,
      queryResult,
      baseGoods,
      dbResult
    }
  }

  return queryResult
}

module.exports = queryJingfenGoods
